<template>
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    v-if="!is_followed"
    @click="onFollowed"
    :loading='loading'
  >关注</van-button>
  <van-button
    class="follow-btn"
    round
    size="small"
    v-else
    @click="onFollowed"
    :loading='loading'
  >已关注</van-button>
</template>

<script>
import { addFollowed, deleteFollow } from '@/api/user.js'
export default {
  data () {
    return {
      loading: false
    }
  },
  model: {
    prop: 'is_followed',
    event: 'updateFollow'
  },
  props: {
    is_followed: {
      type: Boolean,
      required: true
    },
    user_id: {
      type: [Number, String, Object],
      required: true
    }
  },
  created () {

  },

  methods: {
    // 点击关注/取消关注
    async onFollowed () {
      this.loading = true
      try {
        if (this.is_followed) {
          // 已关注 要 取消关注
          await deleteFollow(this.user_id)
        } else {
          // 未关注 要 关注
          await addFollowed(this.user_id)
        }
        this.$emit('updateFollow', !this.is_followed)
      } catch (err) {
        let msg = '操作失败!'
        if (err.response && err.response.status === 400) {
          msg = '不能关注自己!'
        }
        this.$toast(msg)
      }
      this.loading = false
    }
  }
}
</script>

<style scoped lang='less'>

</style>
